package com.yn.demo_redis_lock.task;

import com.yn.demo_redis_lock.redis.RedisPool;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName: TestTask
 * @Description:
 * @author: 王胜
 * @date 2021/4/12
 * @Version: 1.0
 **/
//@Configuration
//@EnableScheduling
public class TestRedissionTask {
    @Value("${server.port}")
    public String ip;
    @Resource
    RedissonClient redisson;
    @Scheduled(cron = "0/1 * * * * *")
    public void testTask() throws InterruptedException {
        RLock lock = redisson.getLock("my-lock");
        if (lock.tryLock(3, TimeUnit.SECONDS)){
            System.out.println("============"+ip+"获得分布式锁成功=======================");
            run();
            //释放锁
            lock.unlock();
            System.out.println("============释放分布式锁成功=======================");

        } else {
            System.out.println("============获得分布式锁失败=======================");
            System.out.println("============"+ip+"机器上占用分布式锁，聚类任务正在执行=======================");
            System.out.println("============本次聚类定时任务结束==============");
            return;
        }
    }

    public void run() {

        System.out.println("执行中"+new Date());
        try {
            Thread.sleep(1000*3 );
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行结束"+new Date());

    }
}
